import HModal from "@/components/ant-ext/HModal";
import { useTableActionRedux } from "@/components/ant-ext-table/redux/HAdminContext";
import { Form } from "antd";
import HFormItem from "@/components/ant-ext/HFormItem";
import SysRole, { SysRoleEntity } from "@/api/sys-role";
import { useActionForm, useHandle, useEdit } from "@/common/hooks";
import SysDepart from "@/api/sys-depart";
import {TreeSelectElement} from "@/common/zct-types";
import {util} from "@/common/util";
import { useEffect, useState } from "react";


export default function RoleEdit() {
    const [loading, setLoading] = useState(false)
    const { action, reset } = useTableActionRedux<SysRoleEntity>()
    const [orgTree, setOrgTree] = useState<TreeSelectElement[]>([])
    const { form, key, title } = useActionForm(action, [SysRole.EDIT], SysRole.MAPPING)
    const close = () => {
        reset()
        form.resetFields()
    }
    const reload = useHandle(() => SysDepart.selectTree({
        setLoading,
        success: (data => {
            const arr: never[] = []
            const treeDataOrgMapping = util.TreeSelectDeptMapping(arr, data[0].children)
            setOrgTree(treeDataOrgMapping)
        })
    }), [setOrgTree])
    const saveAndFlush = useEdit(key === SysRole.EDIT ? SysRole.doEdit : SysRole.doSave, {
        setLoading: setLoading,
        success: () => {
            reset()
        }
    })
    useEffect(() => {
        if (action.match(SysRole.EDIT)) {
            SysRole.selectById({
                params: { id: action.getRow()?.id }, setLoading, success: (data) => {
                    reload()
                    form.setFieldsValue(data)
                }
            })
        }
    }, [action, form])


    return <>

        <HModal onCancel={close} type={"setUp"} style={{ width: "400px", height: "200px" }} confirmLoading={loading}
            onOk={form.submit}
            visible={title !== undefined}
            title={title}
        >
            <Form name={"editForm"} form={form} labelCol={{ sm: 6 }} onFinish={() => {
                saveAndFlush({ body: { ...form.getFieldsValue() } })
            }}>
                <HFormItem label={"角色编码"} name={"id"} hidden={key === SysRole.ADD} disabled={key !== SysRole.ADD} />
                <HFormItem label={"角色名称"} name={"roleName"} required />
                <HFormItem label={"所属部门"} name={"deptId"} type={"treeSelect"} dataSource={orgTree} required />
            </Form>
        </HModal>
    </>
}